package ccgl.com.action;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ccgl.com.model.MUser;
import ccgl.com.server.LoginServer;
import ccgl.com.util.GsonPrint;

public class LoginAction extends BaseServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	HttpServletRequest request = null;
	HttpServletResponse response = null;
	LoginServer server = new LoginServer();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.request = req;
		this.response = resp;
		req.setCharacterEncoding("UTF-8");
		String control = this.request.getParameter("control");
		if ("login".equals(control)) {
			login();
		} else if ("logout".equals(control)) {
			logout();
		} else {
			GsonPrint.printFormatGson("没有请求的control！", this.response);
		}
	}

	private void logout() {
		this.request.getSession().removeAttribute("user");
		try {
			GsonPrint.printFormatGson("已注销", this.response);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void login() {
		MUser user = null;
		String username = this.request.getParameter("username");
		String password = this.request.getParameter("password");

		try {
			user = server.login(username, password);
			if (user != null) {
				this.request.getSession().setAttribute("user", user);
				this.response.sendRedirect("jsp/main.jsp");
			} else {
				this.request.setAttribute("error", "用户名或密码错误！");
				this.request.getRequestDispatcher("/login.jsp").forward(request, response);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
